package com.warrantyhotel.android.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.CountryTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.FindStoresTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.RetailStoresTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.ui.map.IOnZoomListener;
import com.warrantyhotel.android.ui.map.MyMapView;
import com.warrantyhotel.android.ui.map.MyOverlayItem;
import com.warrantyhotel.android.ui.map.PlaceInfo;
import com.warrantyhotel.android.ui.map.PlaceOverlay;
import com.warrantyhotel.android.util.BitmapUtils;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.warrantyhotel.android.util.OnRedirectToListStores;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.imLoader2.Utils;
import com.warrantyhotel.android.widget.CustomImageView;

public class MapActivity extends com.google.android.maps.MapActivity implements Receiver, AsyncQueryListener, OnRedirectToListStores, IOnZoomListener {

	private MyMapView mapView;
	private MapController mapController;
	private MyLocationOverlay whereAmI;
	private List<Overlay> mapOverlays;
	private DetachableResultReceiver receiver;
	private NotifyingAsyncQueryHandler mHandler;
	private static SharedPreferences prefs;
	private LayoutInflater mInflater;
	private HorizontalScrollView mMakesScroll;
	private final static int ANIMATE_TO = 99;
	private String retaiIDFilter = null;
	// private OverlayBuilder ovbuild;
	private TextView header;
	private String retailStoreID = null;

	private PlaceOverlay placeOverlay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_activity);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMakesScroll = (HorizontalScrollView) findViewById(R.id.store_scroll);

		mapView = (MyMapView) findViewById(R.id.map);
		header = (TextView) findViewById(R.id.header);

		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.layout_zoom);
		@SuppressWarnings("deprecation")
		View zoomView = mapView.getZoomControls();
		zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		mapView.displayZoomControls(true);
		mapView.setEnabled(true);
		mapView.setClickable(true);
		mapView.setOnZoomListener(this);
		mapController = mapView.getController();
		mapOverlays = mapView.getOverlays();
		mapView.setReticleDrawMode(MapView.ReticleDrawMode.DRAW_RETICLE_NEVER);
		whereAmI = new MyLocationOverlay(this, mapView);

		mapView.postInvalidate();
		mapOverlays.add(whereAmI);
		// /////////////////////////////////////////
		Drawable placeMarker = this.getResources().getDrawable(R.drawable.rounded);
		placeOverlay = new PlaceOverlay(placeMarker, mapView, this);

		// /////////////////////////////////////////

		final Bundle bundle = getIntent().getExtras();
		if (null != bundle && bundle.containsKey(Keys.longtitude) && bundle.containsKey(Keys.latitude)) {

			retailStoreID = bundle.getString(Keys._retailStoreId);
			retrieveRetailID(retailStoreID);

			double lat = bundle.getDouble(Keys.latitude);
			double lng = bundle.getDouble(Keys.longtitude);

			mapController.animateTo(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
			mapController.setZoom(15);

		} else {
			fetchStoreInScreenRadius();
			retrieveNearbyStores("55", "11", 120000 * 1609, true, true);
			moveToMyLocation();
		}
		nearbyStoresRetrievingFromDBDistinct();

		handleIntent(getIntent());

	}

	@Override
	public void onNewIntent(Intent newIntent) {
		setIntent(newIntent);
		handleIntent(newIntent);

	}

	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			final Intent newIntent = new Intent(this, NearbyStores.class);
			newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			newIntent.putExtra(Keys._query, query);
			startActivity(newIntent);

		} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			choosedStoredFromDB(intent.getData());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_location, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.my_position:
			findMe(null);
			return true;
		case R.id.stores_list:
			showStoresList(null);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void findMe(View view) {
		if (whereAmI != null && null != whereAmI.getMyLocation()) {
			mapController.animateTo(whereAmI.getMyLocation());
			mapController.setZoom(9);
		} else
			ToastUtil.showText(getApplicationContext(), getString(R.string.waiting_for_location));
	}

	public void showStoresList(View view) {
		final Intent intent = new Intent(getApplicationContext(), NearbyStores.class);

		if (null != retaiIDFilter) {
			intent.putExtra(Keys._retailIdFilter, retaiIDFilter);
		}

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		// TODO
		double right_bottom_lat = mapView.getProjection().fromPixels(metrics.widthPixels, mapView.getHeight() - header.getHeight()).getLatitudeE6() / 1E6;
		double right_bottom_lng = mapView.getProjection().fromPixels(metrics.widthPixels, mapView.getHeight() - header.getHeight()).getLongitudeE6() / 1E6;

		double left_bottom_lat = mapView.getProjection().fromPixels(0, mapView.getHeight() - header.getHeight()).getLatitudeE6() / 1E6;
		double left_bottom_lng = mapView.getProjection().fromPixels(0, mapView.getHeight() - header.getHeight()).getLongitudeE6() / 1E6;

		double left_top_lat = mapView.getProjection().fromPixels(0, header.getHeight()).getLatitudeE6() / 1E6;
		double left_top_lng = mapView.getProjection().fromPixels(0, header.getHeight()).getLongitudeE6() / 1E6;

		double right_top_lat = mapView.getProjection().fromPixels(metrics.widthPixels, header.getHeight()).getLatitudeE6() / 1E6;
		double right_top_lng = mapView.getProjection().fromPixels(metrics.widthPixels, header.getHeight()).getLongitudeE6() / 1E6;

		intent.putExtra(NearbyStores.RIGHT_BOTTOM_LAT, right_bottom_lat);
		intent.putExtra(NearbyStores.RIGHT_BOTTOM_LNG, right_bottom_lng);

		intent.putExtra(NearbyStores.LEFT_BOTTOM_LAT, left_bottom_lat);
		intent.putExtra(NearbyStores.LEFT_BOTTOM_LNG, left_bottom_lng);

		intent.putExtra(NearbyStores.LEFT_TOP_LAT, left_top_lat);
		intent.putExtra(NearbyStores.LEFT_TOP_LNG, left_top_lng);

		intent.putExtra(NearbyStores.RIGHT_TOP_LAT, right_top_lat);
		intent.putExtra(NearbyStores.RIGHT_TOP_LNG, right_top_lng);
		intent.putExtra(Keys._retailStoreId, retailStoreID);

		startActivityForResult(intent, ANIMATE_TO);
	}

	/*
	 * public void showAllStores(View view) {
	 * showAllStores.setVisibility(View.GONE);
	 * horizontal_bar.setVisibility(View.VISIBLE);
	 * nearbyStoresRetrievingFromDBDistinct(); fetchStoreInScreenRadius();
	 * retrieveNearbyStores("55", "11", 200, false, true); }
	 */

	// for one store
	private void oneStoreFromDB(String oneRetailStore) {
		String selection = null;
		if (oneRetailStore != null) {
			selection = FindStoresTable.RETAIL_STORE_ID + " = '" + oneRetailStore + "'";
		}
		String[] projectionNearbyStores = { FindStoresTable._ID, FindStoresTable.NAME, FindStoresTable.LOCATION_LATITUDE, FindStoresTable.LOCATION_LONGITUDE,
				FindStoresTable.THUMBNAIL, FindStoresTable.RETAIL_ID, FindStoresTable.RETAIL_STORE_ID, FindStoresTable.BANNER, FindStoresTable.POI };
		mHandler.startQuery(QueriesCodes.NEARBY_STORES, FindStoresTable.CONTENT_URI, projectionNearbyStores, selection, null, null);
	}

	private void nearbyStoresRetrievingFromDB() {
		String selection = null;
		if (retaiIDFilter != null) {
			selection = FindStoresTable.RETAIL_ID + "= '" + retaiIDFilter + "'";
		}
		String[] projectionNearbyStores = { FindStoresTable._ID, FindStoresTable.NAME, FindStoresTable.LOCATION_LATITUDE, FindStoresTable.LOCATION_LONGITUDE,
				FindStoresTable.THUMBNAIL, FindStoresTable.RETAIL_ID, FindStoresTable.RETAIL_STORE_ID, FindStoresTable.BANNER, FindStoresTable.POI };
		mHandler.startQuery(QueriesCodes.NEARBY_STORES, FindStoresTable.CONTENT_URI, projectionNearbyStores, selection, null, null);
	}

	private void choosedStoredFromDB(Uri uri) {
		mHandler.startQuery(QueriesCodes.CHOOSED_STORE, uri, null, FindStoresTable._ID + " = " + uri.getLastPathSegment(), null, null);
	}

	private void nearbyStoresRetrievingFromDBDistinct() {
		String[] projectionNearbyStores = { FindStoresTable.RETAIL_ID, FindStoresTable.THUMBNAIL };
		String selection = null;
		if (retailStoreID != null)
			selection = RetailStoresTable.RETAIL_STORE_ID + " = '" + retailStoreID + "'";

		mHandler.startQuery(QueriesCodes.NEARBY_STORES_DISTINCT, FindStoresTable.CONTENT_URI.buildUpon().appendPath(Keys.distinct).build(),
				projectionNearbyStores, selection, null, Keys.distinct);
	}

	@Override
	protected boolean isLocationDisplayed() {
		return whereAmI.isMyLocationEnabled();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private void moveToMyLocation() {
		final boolean onFirstFix = prefs.getBoolean(Keys.onFirstFix, true);
		whereAmI.enableMyLocation();
		whereAmI.enableCompass();
		whereAmI.runOnFirstFix(new Runnable() {

			@Override
			public void run() {
				if (onFirstFix) {
					final Editor edit = prefs.edit();
					edit.putBoolean(Keys.onFirstFix, false);
					edit.commit();
					mapController.setCenter(whereAmI.getMyLocation());
					mapController.setZoom(12);
				}

			}
		});
	}

	public void onSearch(View view) {
		this.startSearch(null, false, Bundle.EMPTY, false);
	}

	private void retrieveRetailID(String retailStoreId) {
		Intent retailStoresIntent = new Intent(Intent.ACTION_SYNC, CountryTable.CONTENT_URI, this, UpdateIntentService.class);
		retailStoresIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		retailStoresIntent.putExtra(Keys._retailStoreId, retailStoreId);
		retailStoresIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.RETAIL_STORE);
		startService(retailStoresIntent);
	}

	private void retrieveNearbyStores(String lat, String lng, int readius, boolean clearCacheInDb, boolean firstRun) {
		Intent nearbyStoresIntent = new Intent(Intent.ACTION_SYNC, CountryTable.CONTENT_URI, this, UpdateIntentService.class);
		nearbyStoresIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);

		nearbyStoresIntent.putExtra(Keys.latitude, lat);
		nearbyStoresIntent.putExtra(Keys.longtitude, lng);
		// covert meters to miles
		nearbyStoresIntent.putExtra(Keys.radius, (double) readius / 1609);
		nearbyStoresIntent.putExtra(Keys.clearCacheInDb, clearCacheInDb);
		nearbyStoresIntent.putExtra(Keys.firstRun, firstRun);

		nearbyStoresIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.NEARBY_STORES);
		startService(nearbyStoresIntent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// StorePinMapOverlay.count = 0;
		mapOverlays.clear();
		// onFirstFix = 0;
		final Editor edit = prefs.edit();
		edit.putBoolean(Keys.onFirstFix, true);
		edit.commit();
	}

	@Override
	protected void onStop() {
		super.onStop();
		whereAmI.disableMyLocation();
		whereAmI.disableCompass();

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void onMakeScrollLeftClick(View v) {
		mMakesScroll.scrollBy(-50, 0);
	}

	public void onMakeScrollRightClick(View v) {
		mMakesScroll.scrollBy(50, 0);
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			// do nothing
			break;
		case UpdateIntentService.STATUS_ERROR:
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			nearbyStoresRetrievingFromDBDistinct();
			break;

		case UpdateIntentService.STATUS_FINISHED:

			if (resultData.containsKey(Keys.firstRun)) {
				nearbyStoresRetrievingFromDBDistinct();
				fetchStoreInScreenRadius();
			} else if (resultData.containsKey(Keys._retailStoreId)) {
				// TODO
				String[] projectionRetailStores = { RetailStoresTable._ID, RetailStoresTable.ADDRES_SCITY, RetailStoresTable.ADDRESS_POSTAL_CODE,
						RetailStoresTable.ADDRESS_STREET, RetailStoresTable.LATITUDE, RetailStoresTable.LONGTITUDE, RetailStoresTable.NAME,
						RetailStoresTable.PHONE, RetailStoresTable.PHONE_PREFIX, FindStoresTable.SERVICE_EMAIL, FindStoresTable.BANNER,
						FindStoresTable.SERVICE_NUMBER, RetailStoresTable.RETAIL_STORE_ID, RetailStoresTable.ADDRESS_COUNTRY_ID,
						RetailStoresTable.ADDRESS_STATE_ID, RetailStoresTable.BANNER, RetailStoresTable.DESCRIPTION, RetailStoresTable.INFO,
						RetailStoresTable.SERVICE_EMAIL };
				Cursor cursor = getContentResolver().query(RetailStoresTable.CONTENT_URI, projectionRetailStores,
						RetailStoresTable.RETAIL_STORE_ID + " = '" + retailStoreID + "'", null, null);
				if (cursor != null && cursor.moveToFirst()) {
					String lat = cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LATITUDE));
					String lng = cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LONGITUDE));
					Log.e(" ", lat + " " + lng);
					cursor.close();
				}
				oneStoreFromDB(retailStoreID);
			}

			break;
		}
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.NEARBY_STORES:
			if (cursor != null) {

				ArrayList<PlaceInfo> places = new ArrayList<PlaceInfo>();

				PlaceInfo p;
				if (cursor != null && cursor.moveToFirst()) {
					do {
						double lat = Double.valueOf(cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LATITUDE)));
						double lng = Double.valueOf(cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LONGITUDE)));
						String retailStoreId = cursor.getString(cursor.getColumnIndex(FindStoresTable.RETAIL_STORE_ID));
						String name = cursor.getString(cursor.getColumnIndex(FindStoresTable.NAME));
						String thumbnail = cursor.getString(cursor.getColumnIndex(FindStoresTable.THUMBNAIL));
						String banner = cursor.getString(cursor.getColumnIndex(FindStoresTable.BANNER));
						int poi = cursor.getInt(cursor.getColumnIndex(FindStoresTable.POI));
						p = new PlaceInfo();
						p.setLatitude(lat);
						p.setLongitude(lng);
						p.setName(name);
						p.setThimbnail(thumbnail);
						p.setBanner(banner);
						p.setPOI(poi == 1);
						p.setRetailStoreID(retailStoreId);
						places.add(p);
					} while (cursor.moveToNext());
					cursor.close();
				}

				mapOverlays.remove(placeOverlay);
				GeoPoint point = null;
				MyOverlayItem overlayitem = null;
				placeOverlay.clear();
				for (PlaceInfo place : places) {
					point = new GeoPoint((int) (place.getLatitude() * 1E6), (int) (place.getLongitude() * 1E6));
					overlayitem = new MyOverlayItem(point, place.getName(), place.getBanner(), place.getRetailStoreID(), place.getThimbnail(), place.isPOI());
					placeOverlay.addOverlay(overlayitem);
				}
				placeOverlay.calculateItems();
				placeOverlay.doPopulate();
				if (placeOverlay.size() > 0) {
					mapOverlays.add(placeOverlay);
					mapView.postInvalidate();
				}

				// ovbuild = new OverlayBuilder(cursor, mapView,
				// getApplicationContext());
				// ovbuild.setPriority(Thread.NORM_PRIORITY - 1);
				// ovbuild.start();
				// mapView.invalidate();
			}
			break;
		case QueriesCodes.NEARBY_STORES_DISTINCT:
			if (cursor != null) {
				final LinearLayout makesList = (LinearLayout) findViewById(R.id.store_item_scroll);
				makesList.removeAllViews();
				if (cursor.moveToFirst()) {
					do {
						final CustomImageView storeButton = (CustomImageView) mInflater.inflate(R.layout.item_store_button, null);
						String thubnail = cursor.getString(cursor.getColumnIndex(FindStoresTable.THUMBNAIL));
						final String retail_id = cursor.getString(cursor.getColumnIndex(FindStoresTable.RETAIL_ID));

						storeButton.setOnClickListener(new android.view.View.OnClickListener() {
							@Override
							public void onClick(View v) {
								retaiIDFilter = retail_id;
								mapOverlays.clear();
								mapOverlays.add(whereAmI);
								mapView.removeAllViews();
								retailStoreID = null;
								fetchStoreInScreenRadius();
								int childCount = makesList.getChildCount();
								for (int i = 0; i < childCount; i++) {
									View view = makesList.getChildAt(i);
									view.setBackgroundResource(R.drawable.rounded);
								}
								v.setBackgroundResource(R.drawable.rounded_grey);
							}
						});

						// imLoader.DisplayImage(thubnail, storeButton);
						BitmapUtils.fetchImage(getApplicationContext(), thubnail, null, null, new BitmapUtils.OnFetchCompleteListener() {
							public void onFetchComplete(Object cookie, Bitmap result) {
								if (result != null) {
									storeButton.setImageBitmap(Utils.getRoundedCornerImage(Bitmap.createScaledBitmap(result, 60, 60, true)));
									makesList.invalidate();
								}
							}
						});

						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
						params.gravity = Gravity.CENTER_VERTICAL;
						params.setMargins(2, 5, 2, 5);
						makesList.addView(storeButton, params);
					} while (cursor.moveToNext());

				}
				cursor.close();
			}
			break;
		case QueriesCodes.CHOOSED_STORE:
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					double lat = cursor.getDouble(cursor.getColumnIndex(FindStoresTable.LOCATION_LATITUDE));
					double lng = cursor.getDouble(cursor.getColumnIndex(FindStoresTable.LOCATION_LONGITUDE));
					GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
					mapController.animateTo(point);
				}
				cursor.close();
			}
			break;
		}
	}

	// public class OverlayBuilder extends Thread {
	// private Cursor cursor;
	// private MapView mapView;
	// private Context context;
	//
	// public OverlayBuilder(Cursor cursor, MapView mapView, Context context) {
	// this.cursor = cursor;
	// this.mapView = mapView;
	// this.context = context;
	// }
	//
	// @Override
	// public void run() {
	// StorePinMapOverlay storeOverlay;
	//
	// if (cursor.moveToFirst()) {
	// do {
	//
	// double lat =
	// Double.valueOf(cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LATITUDE)));
	// double lng =
	// Double.valueOf(cursor.getString(cursor.getColumnIndex(FindStoresTable.LOCATION_LONGITUDE)));
	//
	// // TODO
	// String thumbnail =
	// cursor.getString(cursor.getColumnIndex(FindStoresTable.THUMBNAIL));
	// String banner =
	// cursor.getString(cursor.getColumnIndex(FindStoresTable.BANNER));
	// String retailStoreId =
	// cursor.getString(cursor.getColumnIndex(FindStoresTable.RETAIL_STORE_ID));
	// storeOverlay = new
	// StorePinMapOverlay(context.getResources().getDrawable(R.drawable.store),
	// MapActivity.this, mapView, retailStoreId, MapActivity.this);
	// StoreItem storeItem = new StoreItem(new GeoPoint((int) (lat * 1E6), (int)
	// (lng * 1E6)), "", "", retailStoreId, thumbnail, banner);
	// storeOverlay.addOverlay(storeItem);
	// handler.sendMessage(handler.obtainMessage(1, storeOverlay));
	// } while (cursor.moveToNext());
	// }
	// cursor.close();
	// }
	//
	// }

	// Handler handler = new Handler() {
	// @Override
	// public void handleMessage(Message msg) {
	// switch (msg.what) {
	// case 1:
	//
	// if (!mapOverlays.contains((StorePinMapOverlay) msg.obj)) {
	// mapOverlays.add((StorePinMapOverlay) msg.obj);
	// }
	// mapView.invalidate();
	// break;
	//
	// default:
	// break;
	// }
	// }
	// };

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case ANIMATE_TO:
				double lat = data.getDoubleExtra(Keys.latitude, 0d);
				double lng = data.getDoubleExtra(Keys.longtitude, 0d);
				mapController.animateTo(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));

				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						fetchStoreInScreenRadius();
					}
				}, 1500);

				break;

			default:
				break;
			}
		}
	}

	private void fetchStoreInScreenRadius() {
		nearbyStoresRetrievingFromDB();
	}

	@Override
	public void redirectToList() {
		showStoresList(null);
	}

	@Override
	public void onZoomChanged() {
		if (placeOverlay != null) {
			placeOverlay.calculateItems();
		}
	}

}
